package cn.player.act.filter;

import android.animation.ObjectAnimator;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;

import com.startchat.filter.filter.FilterManager;
import com.startchat.filter.video.CodecConfig;
import com.startchat.filter.video.IMediaCodec;
import com.startchat.filter.video.MediaCodecHelper;
import com.startchat.filter.video.MediaCodecLHelper;
import com.startchat.filter.video.OnVideoProcessCallback;
import com.startchat.filter.video.VideoPlayRenderer;
import com.startchat.filter.widget.MeasureHelper;
import com.startchat.filter.widget.VideoPlaySurfaceView;

import cn.player.R;
import cn.player.adapter.VideoFilterAdapter;


/**
 * Created by xingliao_zgl on 16/8/16.
 */
public class VideoPlayActivity extends AppCompatActivity implements View.OnClickListener {


    private static String mInputVideoPath = "file:///storage/emulated/0/acvideo/rec_test_face.mp4";
    //    private static final String mInputVideoPath = "file:///storage/emulated/0/acvideo/video_1472270242985.mp4";
    private static String mInputAudioPath = "file:///storage/emulated/0/acvideo/rec_test_face.mp4";


    private VideoPlaySurfaceView mVideoPlaySurfaceView;
    private Button mVideoProcessBtn;
    private VideoPlayRenderer mRender;

    private LinearLayout mLlBottom;
    private Button mBtnFilter;
    private Button mBtnFilterToneCurve;
    private RecyclerView mRcvFilter;
    private VideoFilterAdapter mVideoFilterAdapter;
    private FilterManager.FilterType mCurrentFilterType;
    /**
     * 当前选中的FilterType
     */
    private int mFilterChangePosition;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_play);

//        mInputVideoPath = "android.resource://" + getPackageName() + "/" + R.raw.rec_test_face;//没播出来
        mInputVideoPath = getExternalCacheDir().getPath() + "/rec_test_face.mp4";
        mInputAudioPath = mInputVideoPath;

        mVideoPlaySurfaceView = (VideoPlaySurfaceView) findViewById(R.id.sv_video_play);
        mVideoPlaySurfaceView.setVideoPath(mInputVideoPath);
        mVideoPlaySurfaceView.setLooping(true);
        mVideoPlaySurfaceView.setVideoLayout(MeasureHelper.AR_4_3_FIT_PARENT);
        mRender = mVideoPlaySurfaceView.getRenderer();
        mVideoPlaySurfaceView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
//                startVideoProcess();
            }
        });
        mVideoPlaySurfaceView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mVideoPlaySurfaceView.queueEvent(new Runnable() {
                    @Override
                    public void run() {
                        mRender.setEncodingEnabled(false);
//                        mRender.notifyDestroy();
                    }
                });
            }
        });


        mLlBottom = (LinearLayout) findViewById(R.id.ll_bottom);
        mRcvFilter = (RecyclerView) findViewById(R.id.rcv_filter_list);
        mBtnFilter = (Button) findViewById(R.id.filter_name);
        mBtnFilterToneCurve = (Button) findViewById(R.id.filter_tone_curve);
        mVideoProcessBtn = (Button) findViewById(R.id.video_process);
        mBtnFilter.setOnClickListener(this);
        mBtnFilterToneCurve.setOnClickListener(this);
        mVideoProcessBtn.setOnClickListener(this);
        mVideoPlaySurfaceView.setOnClickListener(this);

    }


    private void setFilterAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRcvFilter.setLayoutManager(linearLayoutManager);
        if (mVideoFilterAdapter == null) {
            mVideoFilterAdapter = new VideoFilterAdapter(this);
            mRcvFilter.setAdapter(mVideoFilterAdapter);
            mVideoFilterAdapter.setOnFilterConfigClickListener(new VideoFilterAdapter.OnFilterConfigClickListener() {
                @Override
                public void onFilterConfigClick(int position, FilterManager.FilterType filterType) {
                    if (mFilterChangePosition != position) {
                        setFilterBg(position, mFilterChangePosition);
                        mFilterChangePosition = position;
                        mVideoPlaySurfaceView.changeFilter(filterType);
                    }
                }
            });
        } else {
            mVideoFilterAdapter.notifyDataSetChanged();
        }
    }

    private void setFilterBg(int newPosition, int currentPosition) {
        mVideoFilterAdapter.setCurrentPosition(newPosition);
        mVideoFilterAdapter.notifyItemChanged(currentPosition);
        mVideoFilterAdapter.notifyItemChanged(newPosition);
    }


    private void animHide(View view, int height) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationY", 0, height);
        animator.setDuration(350);
        animator.start();
    }

    private void animShow(View view, int height) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationY", height, 0);
        animator.setDuration(350);
        animator.start();
    }


    @Override
    protected void onResume() {
        super.onResume();
        mVideoPlaySurfaceView.onResume();
    }

    @Override
    protected void onPause() {
        mVideoPlaySurfaceView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVideoPlaySurfaceView.release();
    }

    private boolean isPaused;

    private long mStartTime;

    private IMediaCodec getMediaCodecHelper() {
        IMediaCodec mediaCodecHelper;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mediaCodecHelper = new MediaCodecLHelper();
        } else {
            mediaCodecHelper = new MediaCodecHelper();
        }

        return mediaCodecHelper;
    }

    private void startVideoProcess() {

        mStartTime = System.currentTimeMillis();
        String outputFilePath = getExternalCacheDir().getPath() + "/video_" + System.currentTimeMillis() + ".mp4";
        IMediaCodec helper = getMediaCodecHelper();

        FilterManager.FilterType filterType = mVideoPlaySurfaceView.getRenderer().getCurrentFilterType();

        CodecConfig config = new CodecConfig(mInputVideoPath, mInputAudioPath, outputFilePath, filterType);
        helper.startProcessVideo(getApplicationContext(), config);
        helper.setOnVideoProcessCallback(new OnVideoProcessCallback() {
            @Override
            public void onVideoProcessComplete() {
                Log.i("zl", "onVideoProcessComplete,execute time: " + (System.currentTimeMillis() - mStartTime) / 1000 + "s");

            }

            @Override
            public void onVideoProcessSuccess() {
                Log.i("zl", "onVideoProcessSuccess");
            }

            @Override
            public void onVideoProcessFailed(String errMsg) {
                Log.i("zl", "onVideoProcessFailed,msg = " + errMsg);
            }

            @Override
            public void onVideoProcessCanceled() {
                Log.i("zl", "onVideoProcessCanceled");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sv_video_play:
                /*if (!isPaused) {
                    isPaused = true;
                    mVideoPlaySurfaceView.pause();
                } else {
                    isPaused = false;
                    mVideoPlaySurfaceView.start();
                }*/
                if (mRcvFilter.getTranslationY() == 0) {
                    animHide(mRcvFilter, getResources().getDimensionPixelOffset(R.dimen.view_height_80));
                    animShow(mLlBottom, getResources().getDimensionPixelOffset(R.dimen.view_height_60));
                }
                break;
            case R.id.filter_name:
                animHide(mLlBottom, getResources().getDimensionPixelOffset(R.dimen.view_height_60));
                animShow(mRcvFilter, getResources().getDimensionPixelOffset(R.dimen.view_height_80));
                setFilterAdapter();
                break;
            case R.id.filter_tone_curve:
                mVideoPlaySurfaceView.changeFilter2(FilterManager.FilterType.ToneCurve);
                break;
            case R.id.video_process:
                startVideoProcess();
                break;
        }
    }
}
